package com.example.data.factory.common.Exception;

import java.util.HashSet;
import java.util.Set;

public class MyException extends RuntimeException {
    private String code;
    private Set<String> errors;

    public MyException() {
        this.code = CommonErrorCode.BUSINESS_ERROR.getCode();
        this.errors = new HashSet<>();
    }

    public MyException(String message) {
        super(message);
        this.code = CommonErrorCode.BUSINESS_ERROR.getCode();
        this.errors = new HashSet<>();
        this.errors.add(message);
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
        this.code = CommonErrorCode.BUSINESS_ERROR.getCode();
        this.errors = new HashSet<>();
        this.errors.add(message);
    }

    public MyException(Throwable cause) {
        super(cause);
        this.code = CommonErrorCode.BUSINESS_ERROR.getCode();
        this.errors = new HashSet<>();
        if (cause != null) {
            this.errors.add(cause.getMessage());
        }
    }

    public MyException(String message, String errorCode) {
        super(message);
        this.code = errorCode; // 直接使用传入的错误码
        this.errors = new HashSet<>();
        this.errors.add(message);
    }

    public MyException(String message, Throwable cause, String errorCode) {
        super(message, cause);
        this.code = errorCode; // 直接使用传入的错误码
        this.errors = new HashSet<>();
        this.errors.add(message);
    }

    public MyException(Throwable cause, String errorCode) {
        super(cause);
        this.code = errorCode; // 直接使用传入的错误码
        this.errors = new HashSet<>();
        if (cause != null) {
            this.errors.add(cause.getMessage());
        }
    }

    public static void throwIt(String message) {
        throw new MyException(message);
    }

    public static void throwIt(String message, String code) {
        throw new MyException(message, code);
    }

    public MyException addError(String msg) {
        this.errors.add(msg);
        return this;
    }

    @Override
    public String getMessage() {
        if (this.errors.isEmpty()) {
            return super.getMessage();
        } else {
            StringBuilder sb = new StringBuilder(this.errors.size() * 15);
            for (String error : this.errors) {
                sb.append(error).append(",");
            }
            sb.deleteCharAt(sb.length() - 1); // 移除最后一个逗号
            return sb.toString();
        }
    }

    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String code() {
        return this.code;
    }

    public String message() {
        return this.getMessage();
    }
}